package com.gz.service;

import com.gz.common.MessageType;
import com.gz.common.User;
import com.gz.common.Message;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class UserClientService {
    private Socket socket;
    private User u = new User();

    //向服务端请求用户在线列表
    public void onlineUserList(){
        Message msg = new Message();
        msg.setMestype(MessageType.MESSAGE_GET_ONLINE_USER);
        msg.setSender(u.getUserId());
        //发送给服务器
        try {
            //得到当前Socket对应的ObjectOutputStream对象
            //考虑多线程用以下方法获取得到当前Socket对应的ObjectOutputStream对象的方法
            //如果直接用socket，那只能用于单线程(如果理解成将这个一个客户端对应一个用户那也可以直接socket)
            ObjectOutputStream oops = new ObjectOutputStream(
                    MangeClientConnectServerThread.getClientConnectServerThread(
                    u.getUserId()).getSocket().getOutputStream());
            oops.writeObject(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //!!!注意，这里不能关闭！！！
        //这里关闭会导致run()里面的ObjectInputStream出现问题
    }

    public void logout(){
        Message msg = new Message();
        msg.setSender(u.getUserId());
        msg.setMestype(MessageType.MESSAGE_CLIENT_EXIT);

        try {
            ObjectOutputStream oops = new ObjectOutputStream(
                    MangeClientConnectServerThread.getClientConnectServerThread(
                            u.getUserId()).getSocket().getOutputStream());
            oops.writeObject(msg);
            System.out.println(u.getUserId()+" 退出系统");
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public boolean checkUser(String userId, String password) {
        u.setUserId(userId);
        u.setPassword(password);
        boolean flag = false;
        try {
//            System.out.println("正在等待服务器接收");
            socket = new Socket(InetAddress.getByName("192.168.119.1"), 9999);//服务器端口号9999
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            //发送用户账号密码
            oos.writeObject(u);//ObjectOutputStream与其他流不同，不用shutdown

            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            //接收用户信息
            Message message = (Message) ois.readObject();
            if (message.getMestype().equals(MessageType.MESSAGE_LOGIN_SUCCEED)) {//如果信息正确，登陆成功后持续通信
                //创建一个和服务器保持通信的线程->创建一个类ClientConnectServerThread
                ClientConnectServerThread c = new ClientConnectServerThread(socket);
                c.start();
                MangeClientConnectServerThread.addClientConnectServerThread(userId,c);
                flag = true;
            } else {
                flag = false;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}